package cn.itsource.myinterceptor;

import cn.itsource.base.util.JwtUtils;
import cn.itsource.base.util.LoginData;
import cn.itsource.base.util.Payload;
import cn.itsource.myinterface.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("token");
        try {
            //我们解密解不了 就会报异常
            Payload<LoginData> loginDataPayload = JwtUtils.checkToken(token);
            LoginData loginData = loginDataPayload.getLoginData();
            //得到自己所有的权限
            List<String> permissions = loginData.getPermissions();
            //疑问我怎么去得到我要访问的接口
            //获取你请求的那个接口的自定义注解
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PreAuthorize annotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);//获取当前接口上的注解
            if(annotation == null){
                return true;
            }else {
                String sn = annotation.sn();
                return permissions.contains(sn);
            }
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");
            e.printStackTrace();
            return false;
        }
        // ture false
        // 什么情况下 返回true
        // 1.拿到redis存储的token就可以返回
        // 什么情况下 返回false

    }
}
